/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if(left == right) return head;
        int len = right - left + 1;
        ListNode dummy(0, nullptr);
        dummy.next = head;
        ListNode* ans = head;
        ListNode* next = head->next, *pre = &dummy;
        while(left-- > 1)
        {
            pre = head;
            head = next;
            if(next) next = next->next;
        }
        ListNode* l = pre;
        pre = nullptr;
        ListNode *littleHead = head;
            
        while(head && len-- > 0)
        {
            head->next = pre;
            pre = head;
            head = next;
            if(next) next = next->next;
        }

        littleHead->next = head;
        if(l) l->next = pre;
        return dummy.next;
    }
};
